﻿using ERPWinFormWork.Login;
using ERPWinFormWork.Sales;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ERPWinFormWork.Common;

namespace ERPWinFormWork
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            var UserName = this.txtName.Text.Trim();
            var UserPass = this.txtPassWord.Text.Trim();


            if (string.IsNullOrEmpty(UserName) && string.IsNullOrEmpty(UserPass))
            {
                MessageBox.Show("账号和密码不能为空，请填写完整！");
                return;
            }


            LoginAsync(UserName, UserPass);

        }


        // 定义用于解析登录响应的模型类
        public class LoginResponse
        {
            public int code { get; set; }          // 状态码（200 表示成功）
            public string msg { get; set; }        // 提示信息
            public string jwt { get; set; }        // 需要保存的 Token
            public UserData data { get; set; }     // 用户详细信息
            public string RefreshToken { get; set; }     // 刷新Token

        }

        // 嵌套的用户信息类
        public class UserData
        {
            public int id { get; set; }
            public string userName { get; set; }
            public string userPass { get; set; }   // 注意：实际项目中建议 API 不要返回密码
            public List<int> roleId { get; set; }
            public int deptId { get; set; }
        }

        // 全局变量用于保存 Token（也可存在配置文件或缓存中）
        private string _jwtToken;

        private string RefreshToken;
        // 可选：保存当前登录用户信息
        private UserData _currentUser;

        private async Task<bool> LoginAsync(string account, string password)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://47.96.9.93:8000/dbdata/");

                // 关键调整：API 返回的是 JSON，需将 Accept 头改为 application/json
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json")
                );


                var queryParams = new Dictionary<string, string>
            {
                { "UserName", account },
                { "UserPass", password }
            };

                string queryString = string.Join("&", queryParams.Select(kv =>
                    $"{kv.Key}={Uri.EscapeDataString(kv.Value)}"));
                string requestUrl = $"api/Management/Loing?{queryString}";

                HttpResponseMessage response = await client.GetAsync(requestUrl);

                if (response.IsSuccessStatusCode)
                {
                    // 读取返回的 JSON 字符串
                    string resultJson = await response.Content.ReadAsStringAsync();

                    // 解析为 LoginResponse 对象（需引用 Newtonsoft.Json 库）
                    var loginResult = JsonConvert.DeserializeObject<LoginResponse>(resultJson);

                    // 判断登录是否成功（code=200 且 jwt 不为空）
                    if (loginResult.code == 200 && !string.IsNullOrEmpty(loginResult.jwt))
                    {
                        // 保存 Token 和用户信息到全局TokenManager

                        TokenManager.JwtToken = loginResult.jwt;
                        TokenManager.RefreshToken = loginResult.RefreshToken;

                        TokenManager.CurrentUser = new UserInfo
                        {
                            Id = loginResult.data.id,
                            UserName = loginResult.data.userName,
                            RoleIds = loginResult.data.roleId,
                            DeptId = loginResult.data.deptId
                        };

                        MessageBox.Show($"登录成功！\n用户：{TokenManager.CurrentUser.UserName}\nToken已保存");

                        this.Hide();

                        Master mainForm = new Master();
                        mainForm.FormClosed += (s, args) => this.Close();
                        mainForm.Show();
                        return true;
                    }
                    else
                    {
                        // 登录失败（如账号密码错误）
                        MessageBox.Show($"登录失败：{loginResult.msg}（状态码：{loginResult.code}）");
                        return false;
                    }
                }

                else
                {
                    MessageBox.Show($"请求失败，状态码：{response.StatusCode}");
                    return false;
                }



            }
        }

        private void btnreset_Click(object sender, EventArgs e)
        {
            this.txtName.Text = "";
            this.txtPassWord.Text = "";
        }
    }
}
